#!/usr/bin/python
# coding:utf-8
__author__ = 'good'
__createday__ = '2015-01-15'

import datetime

import flask
from flask import jsonify
from .. import models
from ..extensions import cache
from flask_restful import Resource
import psutil
import time


# ：访问信息API
class visit_json(Resource):
    def get(self):
        today = datetime.datetime.now().date()
        visits = dict()
        labels = list()
        visit = list()
        attack = list()
        robot = list()
        real = list()
        redata = models.Blog_info.query.order_by(models.Blog_info.date.desc()).limit(15)
        for d in redata:
            visit.append(str(d.visit_day))
            attack.append(str(d.visit_attack_day))
            labels.append(str(d.date)[5:])
            robot.append(str(d.visit_robot_day))
            real.append(str(d.visit_day - d.visit_attack_day - d.visit_robot_day))
        labels.reverse()
        attack.reverse()
        visit.reverse()
        robot.reverse()
        real.reverse()
        for i in range(20 - len(visit)):
            de = datetime.timedelta(days=i + 1)
            labels.append(str(today + de)[5:])
        visits['labels'] = labels
        visits['visit'] = visit
        visits['attack'] = attack
        visits['robot'] = robot
        visits['real'] = real
        return jsonify(visits)


# ：文章信息API
class article_json(Resource):
    def get(self):
        article = dict()
        art = models.Article.count_by_category()
        labels = list()
        datas = list()
        for a in art:
            labels.append(a.name)
            d = {
                'value': a.count,
                'name': a.name
            }
            datas.append(d)
        article['labels'] = labels
        article['datas'] = datas
        return jsonify(article)


# ：日历信息API
class calendar_json(Resource):
    @cache.memoize(unless=True, timeout=60)
    def get(self):
        arg = flask.request.args
        start, stop = arg['start'], arg['end']
        create_article = models.Article.query.filter(models.Article.post_date >= start).filter(
            models.Article.post_date <= stop).all()
        update_article = models.Article.find_edit(start, stop)
        visit = models.Blog_info.query.all()
        comment = models.Comments.query.filter(models.Comments.article_id <> 0).all()
        data = []
        for a in create_article:
            dic = {
                'title': u'新增文章' + a.title,
                'url': flask.url_for('article.show', aid=a.id),
                'start': str(a.post_date)
            }
            data.append(dic)
        for a in update_article:
            dic = {
                'title': u'更新文章' + a.title,
                'url': flask.url_for('article.show', aid=a.id),
                'start': str(a.timestamp)
            }
            data.append(dic)
        for v in visit:
            dic = {
                'title': u'日访问量:' + str(v.visit_day),
                'start': str(v.date)
            }
            data.append(dic)
        for comm in comment:
            dic = {
                'title': comm.name + u'评论' + comm.article.title,
                'url': flask.url_for('article.show', aid=comm.article.id),
                'start': str(comm.timestamp)
            }
            data.append(dic)
        return data


class server_info(Resource):
    def get_cpu(self):
        cpu = psutil.cpu_percent()
        return {'timestamp': int(time.time()),
                'usage': cpu,
                'info': '%s cores' % str(psutil.NUM_CPUS),
                'type': 'cpu',
                'msg': 'success'}

    def get_mem(self):
        phymem = psutil.phymem_usage()
        buffers = getattr(psutil, 'phymem_buffers', lambda: 0)()
        cached = getattr(psutil, 'cached_phymem', lambda: 0)()
        used = phymem.total - (phymem.free + buffers + cached)
        return {'timestamp': int(time.time()),
                'usage': phymem.percent,
                'info': str(int(used / 1024 / 1024)) + "M/" + str(int(phymem.total / 1024 / 1024)) + "M",
                'type': 'mem',
                'msg': 'success'}

    def get_net(self):
        netinfo1 = psutil.network_io_counters()
        time.sleep(1)
        netinfo2 = psutil.network_io_counters()
        sent = self.bytes2human(netinfo2.bytes_sent - netinfo1.bytes_sent)
        recv = self.bytes2human(netinfo2.bytes_recv - netinfo1.bytes_recv)

        return {'timestamp': int(time.time()),
                'sent': sent[0],
                'sent_unit': sent[1],
                'recv': recv[0],
                'recv_unit': recv[1],
                'type': 'net',
                'info': len(psutil.network_io_counters(pernic=True)),
                'msg': 'success'
                }

    def get(self, type):
        if type == 'cpu':
            return self.get_cpu()
        elif type == 'mem':
            return self.get_mem
        elif type == 'net':
            return self.get_net()
        elif type == 'all':
            return {
                'cpu': self.get_cpu(),
                'mem': self.get_mem(),
                'net': self.get_net(),
                'type': type,
                'boot_time': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(psutil.boot_time())),
                'timestamp': int(time.time())
            }
        else:
            return {'status': '0',
                    'msg': 'type error',
                    'type': type}

    def bytes2human(self, n):
        symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
        prefix = {}
        for i, s in enumerate(symbols):
            prefix[s] = 1 << (i + 1) * 10
        for s in reversed(symbols):
            if n >= prefix[s]:
                value = float(n) / prefix[s]
                return ['%.2f' % value, s]
        return ['%.2f' % n, 'B']
